package com.ido.alipay.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;

/**
 * Create by zoub
 * Date 2025/8/12 3:42 PM
 */
@Slf4j
public class AliPayUtils {

    /**
     * 解密
     *
     * @param response
     * @return
     */
    public static String decryptData(String response, AlipayConfig alipayConfig) {
        //1. 获取验签和解密所需要的参数
        //参数转换成json格式
        JSONObject jsonObject = JSON.parseObject(response);
        String sign = jsonObject.getString("sign");
        String content = jsonObject.getString("response");
        String signType = "RSA2";
        String charset = "UTF-8";
        String encryptType = "AES";

        //判断是否为加密内容
        boolean isDataEncrypted = !content.startsWith("{");
        boolean signCheckPass = false;
        //2. 验签
        String signContent = content;
        // 支付宝公钥
        String signVeriKey = alipayConfig.getAlipayPublicKey();
        // 接口加解密钥
        String decryptKey = alipayConfig.getEncryptKey();
        //如果是加密的报文则需要在密文的前后添加双引号
        if (isDataEncrypted) {
            signContent = "\"" + signContent + "\"";
        }
        try {
            signCheckPass = AlipaySignature.rsaCheck(signContent, sign, signVeriKey, charset, signType);
        } catch (AlipayApiException e) {
            //验签异常, 日志
        }
        if (!signCheckPass) {
            //验签不通过（异常或者报文被篡改），终止流程（不需要做解密）
            throw new RuntimeException("验签失败");
        }
        //3. 解密
        String plainData = null;
        if (isDataEncrypted) {
            try {
                plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
                System.out.println("解密信息plainData:" + plainData);
            } catch (AlipayApiException e) {
                //解密异常, 记录日志
                throw new RuntimeException("解密异常");
            }
        } else {
            plainData = content;
        }
        log.info("plainData: {}", plainData);
        return plainData;
    }
}

